﻿using Entity;
using Entity.CheckInEntity;
using Entity.ResultModel;
using HotelDAL.CheckInDAL;
using IHotelBLL.ICheckInBLL;
using IHotelDAL;
using IHotelDAL.ICheckInDAL;
using IHotelDAL.IFrondeskDAL;
using IHotelDAL.IRoomDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HotelBLL.CheckInBLL
{
    public class CheckInBLL : ICheckInBLL
    {
        ICheckInDAL _checkInDAL;
        IRoomInfoDAL _roomDAL;
        IUserInfoDAL _customter;
        IAppointmentDAL _appointmentDAL;
        IFrontDeskDAL _frontDeskDAL;
        public CheckInBLL(ICheckInDAL checkInDAL, IRoomInfoDAL roomDAL, IAppointmentDAL appointmentDAL, IUserInfoDAL customer, IFrontDeskDAL frontDesk)
        {
            _checkInDAL = checkInDAL;
            _roomDAL = roomDAL;
            _appointmentDAL = appointmentDAL;
            _customter = customer;
            _frontDeskDAL = frontDesk;
        }
        /// <summary>
        /// 添加入住记录
        /// </summary>
        /// <param name="roomId"></param>
        /// <param name="amount"></param>
        /// <param name="creator"></param>
        /// <param name="ID_Card"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool AddCheckInRecord(string roomId, decimal amount, string creator, string Name, string ID_Card, out string msg)
        {
            var room = _roomDAL.GetEntities().Where(r => r.Id == roomId).FirstOrDefault();
            if (room != null && room.Status == Entity.Enum.RoomStatusEnum.已入住)
            {
                msg = "房间已有人入住";
                return false;
            }
            DateTime CheckInDate = DateTime.Now.AddDays(1);
            if (room.Status == Entity.Enum.RoomStatusEnum.已预约)
            {
                var appointment = _appointmentDAL.GetEntities().Where(a => a.RoomId == roomId).FirstOrDefault();
                if (CheckInDate > appointment.CheckInDate)
                {
                    msg = "已有顾客预约明日入住,无法办理入住";
                    return false;
                }
            }
            var dbcontext = _checkInDAL.GetContext();
            bool Success = false;
            using (var transation = dbcontext.Database.BeginTransaction())
            {
                try
                {
                    CheckIn checkIn = new CheckIn()
                    {
                        RoomId = roomId,
                        CheckInDate = DateTime.Now,
                        Amount = amount,
                        Creartor = creator,
                        Id = Guid.NewGuid().ToString(),
                        ID_Card = ID_Card,
                        CheckOutDate = DateTime.Now.AddDays(1),
                        Name = Name,
                        CheckInStatus =  Entity.Enum.CheckInStatus.已入住,
                    };
                    room.Status = Entity.Enum.RoomStatusEnum.已入住;
                    bool isSuccess = _checkInDAL.CreateEntity(checkIn);
                    bool ChangRoomStatus = _roomDAL.UpdateEntity(room);
                    if (!isSuccess || !ChangRoomStatus)
                    {
                        transation.Rollback();
                    }
                    else
                    {
                        Success = true;
                        transation.Commit();
                    }
                }
                catch (Exception)
                {
                    msg = "出现异常，请查看日志";
                    transation.Rollback();
                    return false;
                }
            }
            msg = Success ? "处理成功" : "处理失败";
            return Success;
        }
        /// <summary>
        /// 退房
        /// </summary>
        /// <param name="ID_Card"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool CheckOut(string id, out string msg)
        {
            var checkIn = _checkInDAL.GetEntities().Where(c => c.Id == id).FirstOrDefault();
            if (checkIn == null)
            {
                msg = "未找到用户入住信息";
                return false;
            }
            var dbcontext = _checkInDAL.GetContext();
            bool Success = false;
            using (var transation = dbcontext.Database.BeginTransaction())
            {
                try
                {
                    checkIn.CheckOutDate = DateTime.Now;
                    checkIn.CheckInStatus = Entity.Enum.CheckInStatus.已退房;
                    var room = _roomDAL.GetEntities().Where(r => r.Id == checkIn.RoomId).FirstOrDefault();
                    room.Status = Entity.Enum.RoomStatusEnum.清洁中;
                    bool isSuccess = _checkInDAL.UpdateEntity(checkIn);
                    bool ChangRoomStatus = _roomDAL.UpdateEntity(room);
                    if (!isSuccess && !ChangRoomStatus)
                    {
                        transation.Rollback();
                    }
                    else
                    {
                        transation.Commit();
                        Success = true;
                    }
                }
                catch (Exception)
                {
                    msg = "出现异常,请查看日志";
                    return false;
                }

            }
            msg = Success ? "退房成功" : "退房失败，请联系管理员";
            return Success;
        }
        /// <summary>
        /// 预约客户入住
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="appointmentId"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool AddAppointmentCheckInRecord(string creator, string id, out string msg)
        {
            var appointment = _appointmentDAL.GetEntities().Where(a=>a.Id == id).FirstOrDefault();
            
            if (appointment == null)
            {
                msg = "未找到预约订单";
                return false;
            }
            var customer = _customter.GetEntities().Where(c => c.Id == appointment.UserId).FirstOrDefault();
            if (customer is null)
            {
                msg = "未找到用户信息";
                return false;
            }
            bool isSuccess = false;
            using (var trasation = _checkInDAL.GetContext().Database.BeginTransaction())
            {
                try
                {
                    appointment.Status = Entity.Enum.AppointmentStatusEnum.客户已入住;
                    var room = _roomDAL.GetEntities().Where(r => r.Id == appointment.RoomId).FirstOrDefault();
                    room.Status = Entity.Enum.RoomStatusEnum.已入住;
                    CheckIn checkIn = new CheckIn()
                    {
                        Id = Guid.NewGuid().ToString(),
                        AppointmentId = appointment.Id,
                        Amount = appointment.Amount,
                        IsAppointment = true,
                        CheckInDate = DateTime.Now,
                        CheckOutDate = DateTime.Now.AddDays(1),
                        Creartor = creator,
                        Name = customer.Name,
                        CheckInStatus = Entity.Enum.CheckInStatus.已入住,
                        ID_Card = customer.ID_Card,
                        RoomId = appointment.RoomId,
                    };
                    bool ChangeRoomStatus = _roomDAL.UpdateEntity(room);
                    bool CheckInStatus = _checkInDAL.CreateEntity(checkIn);
                    if (CheckInStatus && ChangeRoomStatus)
                    {
                        isSuccess = true;
                        trasation.Commit();
                    }
                    else
                    {
                        trasation.Rollback();
                    }
                }
                catch (Exception)
                {
                    msg = "办理入住时出现了异常";
                    return false;
                }
            }
            msg = isSuccess ? "办理入住成功" : "办理入住失败";
            return isSuccess;
        }

        public bool ChangeTheRoom(string ID_Card, string roomId, string reason, out string msg)
        {
            var checkIn = _checkInDAL.GetEntities().Where(c => c.Id == ID_Card).FirstOrDefault();
            if (checkIn is null)
            {
                msg = "未找到用户信息";
                return false;
            }
            if (roomId == checkIn.RoomId)
            {
                msg = "房号未修改，无需更改";
                return false;
            }
            using (var transaction = _checkInDAL.GetContext().Database.BeginTransaction())
            {
                try
                {
                    checkIn.RoomId = roomId;
                    bool ChangeRoomStatus = _checkInDAL.UpdateEntity(checkIn);
                    Appointment appointment;
                    if (checkIn.IsAppointment)
                    {
                        appointment = _appointmentDAL.GetEntities().Where(a => a.UserId == _customter.GetEntities().Where(c => c.ID_Card == ID_Card).FirstOrDefault().Id).FirstOrDefault();
                        bool ChangeAppointmentStatus = _appointmentDAL.UpdateEntity(appointment);
                        if (ChangeAppointmentStatus)
                        {
                            ChangeRoomStatus = ChangeAppointmentStatus;
                        }
                    }
                    if (ChangeRoomStatus)
                    {
                        transaction.Commit();
                        msg = "修改成功";
                        return true;
                    }
                    transaction.Rollback();
                    msg = "修改失败";
                    return false;
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    msg = "程序运行时出现了异常";
                    return false;
                }

            }


        }

        public List<ResultCheckIn> GetCheckIn(int page, int limit, out int count)
        {
            var data = (from c1 in _checkInDAL.GetEntities()
                        join r1 in _roomDAL.GetEntities()
                        on c1.RoomId equals r1.Id
                        join f1 in _frontDeskDAL.GetEntities()
                        on c1.Creartor equals f1.Id
                        select new ResultCheckIn
                        {
                            Id = c1.Id,
                            Name = r1.Name,
                            CustomerName = c1.Name,
                            EmployeeName = f1.EmployeeName,
                            CheckInDate = c1.CheckInDate.ToString("yyyy-MM-dd"),
                            CheckOutDate = c1.CheckOutDate.ToString("yyyy-MM-dd"),
                            Amount = c1.Amount,
                            checkInStatus = c1.CheckInStatus.ToString(),
                        }).ToList();
            count = data.Count();
            return data;
        }

        public CheckIn GetCheckIn(string id)
        {
            return _checkInDAL.GetEntities().Where(x => x.Id == id).FirstOrDefault();
        }

        public List<SelectOptionModel> GetRoomTypeOptions()
        {
            return _roomDAL.GetEntities().Select(c => new SelectOptionModel()
            {
                Id = c.Id,
                Name = c.Name
            }).ToList();
        }
    
        public CheckIn GetcheckById(string id)
        {

            return _checkInDAL.GetEntities().FirstOrDefault(c => c.Id == id);
        }

        public bool UpdateCheckIn(string id, decimal amount, string name, string iD_Card, out string msg)
        {

            CheckIn checkIn = _checkInDAL.GetEntities().FirstOrDefault(c => c.Id == id);
            if (checkIn == null)
            {
                msg = "未查询到需要修改";
                return false;
            }

            checkIn.Amount = amount;
            checkIn.Name = name;
            checkIn.ID_Card = iD_Card;



            bool isSuccess = _checkInDAL.UpdateEntity(checkIn);
            if (isSuccess)
            {
                msg = "修改成功";
                return true;
            }
            else
            {
                msg = "修改失败";
                return true;
            }
        }
    }
}
